package org.netconsole.dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.netconsole.model.SystemInformation;

public class SystemInformationDAOImpl implements SystemInformationDAO {
	
    private SessionFactory sf;

    public SystemInformationDAOImpl(SessionFactory sf){
            this.sf = sf;
    }

    public SystemInformationDAOImpl() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public SystemInformation insertSystemInformation(SystemInformation sysInf) {
        try{
            Session session = sf.openSession();
            session.beginTransaction();
            session.save(sysInf);
            session.getTransaction().commit();
        } catch (Exception e){

        }

        return sysInf;
    }

    @Override
    public List<SystemInformation> listSystemInformationById(int eq_id) {
        List<SystemInformation> lst = new ArrayList<SystemInformation>();
        Session session = sf.openSession();
        lst = session.createQuery("from SystemInformation").list();
        for (int i=0; i<lst.size(); i++){
            Session s = sf.openSession();
            Query q = s.createQuery("from SystemInformation where eq_id=:eq_id");
            q.setString("eq_id", Integer.toString(eq_id));
            lst.get(i).setListProcess(q.list());            
        }
        return lst;
    }

    @Override
    public SystemInformation getSystemInformationById(int inf_id) {
            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("from SystemInformation where inf_id=:inf_id");
            query.setString("inf_id", Integer.toString(inf_id));
            SystemInformation sysInf = (SystemInformation) query.uniqueResult();
            Session s = sf.openSession();
            
            Query q = s.createQuery("from Process where inf_id=:inf_id");
            q.setString("inf_id", Long.toString(sysInf.getInf_id()));
            sysInf.setListProcess(q.list());
            if(sysInf != null){
                    System.out.println("User Retrieved from DB::"+ sysInf);
            }
            tx.commit();session.close();
            return sysInf;
    }


}
